"""
滑动拼图验证码
使用程序通过滑动拼图验证码的校验
目标站点：http://www.porters.vip/captcha/jigsaw.html
"""
import re
import time
import os
from selenium import webdriver

DIR_NAME = os.path.abspath(os.path.join(os.getcwd(), '..'))
DRIVER_EXE = os.path.join(DIR_NAME, 'utils', 'chromedriver')

# todo 1.打开页面并定位滑块元素
driver = webdriver.Chrome(executable_path=DRIVER_EXE)
driver.get('http://www.porters.vip/captcha/jigsaw.html')
driver.maximize_window()
# 定位滑块
sliders = driver.find_element_by_css_selector('#jigsawCircle')

# todo 2.点击滑块并保持不松开
action = webdriver.ActionChains(driver)
action.click_and_hold(sliders).perform()
time.sleep(5)

# todo 3.获取覆盖矩形和缺口的css样式信息
mbk_style = driver.find_element_by_css_selector('#missblock').get_attribute('style')     # todo 覆盖矩形样式
tbk_style = driver.find_element_by_css_selector('#targetblock').get_attribute('style')   # todo 缺口样式
# todo 覆盖矩形left
mbk_left = float(re.search(re.compile(r'.*?left:(.*?)px.*?', re.DOTALL), mbk_style).group(1).strip())
# todo 缺口left
tbk_left = float(re.search(re.compile(r'.*?left:(.*?)px.*?', re.DOTALL), tbk_style).group(1).strip())

# todo 4.计算当前滑块需要移动的距离
distance = tbk_left - mbk_left

# todo 5.执行滑动
action.move_by_offset(distance, 0)  # todo 滑动
action.release().perform()  # todo 松开鼠标

time.sleep(3)
driver.close()
